package genesis.familytree.server.common.code.builder;


import genesis.familytree.server.common.code.*;
import genesis.familytree.server.common.exception.ExpressionException;

import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 *
 */
public class NumberExprBuilder extends AbstractDataTypeBuilder implements DataTypeBuilder, DataNameBuilder {


    @Override
    public String build(String name, String format, Params params) throws ExpressionException {
        if (null == format) {
            throw new IllegalArgumentException("param[{" + name + "}] number format not found");
        }

        Object obj = getValue(name, params);

        NumberFormat df = new DecimalFormat(format);
        return df.format(obj);
    }

    @Override
    public Attribute build(Expression expr, int startIndex, int endIndex, String expression) {
        if (!expression.contains(":")) {
            return null;
        }

        String[] str = expression.split(":", 3);
        if (str.length != 3) {
            return null;
        }
        if (!"number".equals(str[1])) {
            return null;
        }
        return new Attribute(expr, startIndex, endIndex, str[0], str[1], str[2]);
    }

}
